#include <stdio.h>
#include <stdlib.h>

// 合并两个整数数组，返回动态分配的新数组指针（需手动free）
// 若输入数组为NULL，视为长度为0的数组处理
int* mergeArrays(int* arr1, int* arr2, size_t len1, size_t len2) {
    // 计算总长度（处理NULL时视为长度0）
    size_t totalLen = len1 + len2;
    if (totalLen == 0) {
        printf("Both arrays are empty.\n");
        return NULL;
    }

    // 动态分配内存
    int* merged = (int*)malloc(totalLen * sizeof(int));
    if (merged == NULL) {
        printf("Memory allocation failed.\n");
        return NULL;
    }

    // 复制第一个数组
    for (size_t i = 0; i < len1; i++) {
        merged[i] = arr1[i];
    }
    // 复制第二个数组
    for (size_t j = 0; j < len2; j++) {
        merged[len1 + j] = arr2[j];
    }

    return merged;
}

int main() {
    int arr1[] = {5, 1, 3, 5, 7, 9};
    int arr2[] = {4, 2, 4, 6, 8};
    size_t len1 = sizeof(arr1) / sizeof(arr1[0]);
    size_t len2 = sizeof(arr2) / sizeof(arr2[0]);

    int* merged = mergeArrays(arr1, arr2, len1, len2);
    if (merged != NULL) {
        printf("Merged Array: ");
        for (size_t i = 0; i < len1 + len2; i++) {
            // 仅在非最后一个元素后加空格
            printf("%d%c", merged[i], (i == len1 + len2 - 1) ? '\n' : ' ');
        }
        free(merged);  // 释放动态内存
    }

    return 0;
}